<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" :model="queryParams" layout="inline" :label-col="{style:{width: '100px'}}">
              <a-form-item label="岗位编码" name="postCode">
                <a-input v-model:value="queryParams.postCode" allow-clear placeholder="请输入"
                          @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="类别编码" name="postCategory">
                <a-input v-model:value="queryParams.postCategory" allow-clear
                          placeholder="请输入" @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="岗位名称" name="postName">
                <a-input v-model:value="queryParams.postName" allow-clear placeholder="请输入岗位名称"
                          @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="部门" name="deptId">
                <a-tree-select
                  v-model:value="queryParams.deptId"
                  :tree-data="deptOptions" allow-clear treeLine
                  :field-names="{ value: 'id', label: 'label', children: 'children' }"
                  placeholder="请选择部门"
                  @change="handleQuery"
                />
              </a-form-item>
              <a-form-item label="状态" name="status">
                <a-select v-model="queryParams.status" allow-clear placeholder="岗位状态" @change="handleQuery"
                          :options="sys_normal_disable" :field-names="{label: 'label', value: 'value'}">
                  <template #option="{ label, value }">
                    <a-flex justify="space-between">
                      <span>{{ label }}</span>
                      <span style="color: #999">{{ value }}</span>
                    </a-flex>
                  </template>
                </a-select>
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                        @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                        @click="resetQuery">重置
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>

    <el-row :gutter="12">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24">
        <el-card class="my-tree" shadow="hover" style="height: 100%;overflow-y: auto">
          <el-input v-model="deptName" clearable placeholder="请输入部门名称" prefix-icon="Search" />
          <el-tree
            ref="deptTreeRef"
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="{ label: 'label', children: 'children' }"
            class="mt-2"
            default-expand-all
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          >
            <template #default="scope">
              <el-text>{{ scope.data.label }}</el-text>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <a-card ref="cardRef" class="card-content" hoverable>
          <template #title>
            <el-row ref="headerRef" :gutter="10">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:add']" round icon="Plus" plain type="primary" @click="handleAdd">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:edit']" round :disabled="single" icon="Edit" plain type="success"
                           @click="handleUpdate()"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:remove']" round plain :disabled="multiple" icon="Delete" type="danger"
                           @click="handleDelete()">
                  删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:export']" round icon="Download" plain type="warning"
                           @click="handleExport">导出
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <a-spin :spinning="loading" size="large">
            <el-table :data="postList" :height="tableHeight"
                      @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" min-width="55" />
              <el-table-column align="center" label="序号" type="index" min-width="50">
                <template #default="scope">
                  <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="false" align="center" label="岗位编号" min-width="200" prop="postId" />
              <el-table-column align="center" label="岗位编码" min-width="120" prop="postCode" />
              <el-table-column align="center" label="类别编码" min-width="120" prop="postCategory" />
              <el-table-column :show-overflow-tooltip="true" align="center" label="岗位名称" min-width="150"
                               prop="postName" />
              <el-table-column :show-overflow-tooltip="true" align="center" label="部门" min-width="150"
                               prop="deptName" />
              <el-table-column align="center" label="排序" min-width="80" prop="postSort" />
              <el-table-column align="center" label="状态" min-width="80" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>
              <el-table-column align="center" label="创建时间" prop="createTime" width="180">
              <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
              <el-table-column align="center" fixed="right" label="操作"
                               width="130">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                    <el-button v-hasPermi="['system:post:edit']" circle icon="Edit" plain type="success"
                               @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button v-hasPermi="['system:post:remove']" circle plain icon="Delete" type="danger"
                               @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
              <template #empty>
                <a-empty />
              </template>
          </el-table>
          </a-spin>
        </a-card>
        <a-card hoverable ref="paginationRef" v-show="total>0">
          <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                      :total="total" @pagination="getList" />
        </a-card>

        <!-- 添加或修改岗位对话框 -->
        <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-body close-on-click-modal size="30%">
          <el-form ref="postFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="form.postName" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                check-strictly
                placeholder="请选择部门"
                value-key="id"
              />
            </el-form-item>
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入编码名称" />
            </el-form-item>
            <el-form-item label="类别编码" prop="postCategory">
              <el-input v-model="form.postCategory" placeholder="请输入类别编码" />
            </el-form-item>
            <el-form-item label="岗位顺序" prop="postSort">
              <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
            </el-form-item>
            <el-form-item label="岗位状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-drawer>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Post" lang="ts">
import { listPost, addPost, delPost, getPost, updatePost } from '@/api/system/post';
import { PostForm, PostQuery, PostVO } from '@/api/system/post/types';
import { DeptVO } from '@/api/system/dept/types';
import api from '@/api/system/user';

import { useElTableHeight } from '@/utils/useElTableHeight';
import useSettingsStore from '@/store/modules/settings';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);
// console.log(headerRef.value)
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const postList = ref<PostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);
const deptTreeRef = ref<ElTreeInstance>();
const postFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const initFormData: PostForm = {
  postId: undefined,
  deptId: undefined,
  postCode: '',
  postName: '',
  postCategory: '',
  postSort: 0,
  status: '0',
  remark: ''
};

const data = reactive<PageData<PostForm, PostQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    postCode: '',
    postName: '',
    postCategory: '',
    status: ''
  },
  rules: {
    postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
    postCode: [{ required: true, message: '岗位编码不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
    postSort: [{ required: true, message: '岗位顺序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs<PageData<PostForm, PostQuery>>(data);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.belongDeptId = data.id;
  queryParams.value.deptId = undefined;
  handleQuery();
};

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPost(queryParams.value);
  postList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  postFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (queryParams.value.deptId) {
    queryParams.value.belongDeptId = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  /** 清空左边部门树选中值 */
  queryParams.value.belongDeptId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PostVO[]) => {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  drawer.visible = true;
  drawer.title = '添加岗位';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PostVO) => {
  reset();
  const postId = row?.postId || ids.value[0];
  const res = await getPost(postId);
  Object.assign(form.value, res.data);
  drawer.visible = true;
  drawer.title = '修改岗位';
};

/** 提交按钮 */
const submitForm = () => {
  postFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.postId ? await updatePost(form.value) : await addPost(form.value);
      proxy?.$modal.notifySuccess('操作成功');
      drawer.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PostVO) => {
  const postIds = row?.postId || ids.value;
  await proxy?.$modal.confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？');
  await delPost(postIds);
  await getList();
  proxy?.$modal.notifySuccess('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/post/export',
    {
      ...queryParams.value
    },
    `post_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getTreeSelect(); // 初始化部门数据
  getList();
});
</script>
